﻿using DailyApp.WebAPI.DTOs;
using DailyApp.WPF.Helpers;
using DailyApp.WPF.HttpClients;
using DailyApp.WPF.MsgEvents;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace DailyApp.WPF.ViewModels
{
    internal class LoginUCViewModel : BindableBase, IDialogAware
    {

        #region 声明信息

        //默认的登陆界面的标题
        public string Title { get; set; } = "登陆界面";

        //窗体关闭事件（订阅）
        public event Action<IDialogResult> RequestClose;

        //client
        private readonly HttpRestClient httpRestClient;

        //时间生成器
        private readonly IEventAggregator eventAggregator;

        #endregion


        #region 属性

        //登陆界面切换的属性
        private string loginSelectIndex;

        public string LoginSelectIndex
        {
            get
            {
                return loginSelectIndex;
            }
            set
            {
                loginSelectIndex = value;
                RaisePropertyChanged();
            }
        }

        //账号属性
        private string account;

        public string Account
        {
            get { return account; }
            set
            {
                account = value;
                RaisePropertyChanged();
            }
        }

        //密码属性
        private string pwd;

        public string Pwd
        {
            get { return pwd; }
            set
            {
                pwd = value;
                RaisePropertyChanged();
            }
        }

        //注册信息属性
        private AccountInfoDTO myAccountInfoDTO;

        public AccountInfoDTO MyAccountInfoDTO
        {
            get { return myAccountInfoDTO; }
            set
            {
                myAccountInfoDTO = value;
                RaisePropertyChanged();
            }
        }

        #endregion


        #region 委托命令

        //登陆系统的命令
        public DelegateCommand LoginSystemCmd { get; set; }

        //切换登录界面至注册界面的命令
        public DelegateCommand LoginToSignCmd { get; set; }

        //注册账号的命令
        public DelegateCommand RegesterCmd { get; set; }

        #endregion


        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginUCViewModel(HttpRestClient _httpRestClient, IEventAggregator _eventAggregator)
        {
            //初始化属性
            MyAccountInfoDTO = new AccountInfoDTO();

            //依赖注入服务获取
            httpRestClient = _httpRestClient;
            eventAggregator = _eventAggregator;

            //绑定命令
            LoginToSignCmd = new DelegateCommand(LoginToSignFunc);
            LoginSystemCmd = new DelegateCommand(LoginSystemFunc);
            RegesterCmd = new DelegateCommand(RegesterFunc);
            BtnMinCmd = new DelegateCommand(BtnMinFunc);
            BtnCloseCmd = new DelegateCommand(BtnCloseFunc);
            KeyDownLoginCmd = new DelegateCommand(KeyDownLoginFunc);
        }


        #region 委托的具体方法

        //登陆的具体方法
        private async void LoginSystemFunc()
        {
            //逻辑判断
            if (string.IsNullOrEmpty(Account) || string.IsNullOrEmpty(Pwd))
            {
                eventAggregator.GetEvent<MsgEvent>().Publish("账号信息不全！");
                return;
            }


            //配置apirequest信息
            ApiRequest apiRequest = new ApiRequest();
            apiRequest.Method = Method.GET;
            Pwd = Md5Helper.GetMd5(Pwd);
            apiRequest.Route = $"Account/Login?account={Account}&pwd={Pwd}";//get方法为字符串查询，需将参数填入路由中

            //请求
            var res = await httpRestClient.ExecuteAsync(apiRequest);

            if (res.ResultCode == 1)//登陆成功
            {
                //反序列化
                AccountInfoDTO loginInfo = JsonConvert.DeserializeObject<AccountInfoDTO>(res.ResultData.ToString());

                //传递委托参数
                //List<string> str = ["小明","小红" ];---这是C#12 .NET 8 的新特性
                var param = new DialogParameters
                {
                    { "LoginName", loginInfo.Name }
                };

                //将参数通过对话框传递至主界面
                RequestClose?.Invoke(new DialogResult(ButtonResult.OK, param));
                eventAggregator.GetEvent<MsgEvent>().Publish(res.ResultMsg);
            }
            else//登录失败
            {
                eventAggregator.GetEvent<MsgEvent>().Publish(res.ResultMsg);

                //重置密码
                Account = "";
                Pwd = "";
            }
            return;
        }

        //切换登陆界面的方法
        private void LoginToSignFunc()
        {
            if (LoginSelectIndex == "0")
                LoginSelectIndex = "1";
            else
                LoginSelectIndex = "0";
        }

        //注册的具体方法
        private async void RegesterFunc()
        {
            //数据基本验证
            if (string.IsNullOrEmpty(MyAccountInfoDTO.Name) ||
                string.IsNullOrEmpty(MyAccountInfoDTO.Account) ||
                string.IsNullOrEmpty(MyAccountInfoDTO.Password) ||
                string.IsNullOrEmpty(MyAccountInfoDTO.ConfirmPassWord))
            {
                eventAggregator.GetEvent<MsgEvent>().Publish("注册信息项有空!");
                return;
            }

            //密码应一致
            if (MyAccountInfoDTO.Password != MyAccountInfoDTO.ConfirmPassWord)
            {
                eventAggregator.GetEvent<MsgEvent>().Publish("两次密码不一致，请重新输入!");
                return;
            }

            //配置信息
            ApiRequest apiRequest = new ApiRequest();
            apiRequest.Method = RestSharp.Method.POST;
            apiRequest.Route = "Account/Registered";

            //MD5加密
            myAccountInfoDTO.Password = Md5Helper.GetMd5(MyAccountInfoDTO.Password);
            myAccountInfoDTO.ConfirmPassWord = "";
            apiRequest.Parameters = MyAccountInfoDTO;

            //调用API
            ApiResponse apiResponse = await httpRestClient.ExecuteAsync(apiRequest);

            if (apiResponse.ResultCode == 1)
            {
                eventAggregator.GetEvent<MsgEvent>().Publish("注册成功!");
            }
            else
            {
                eventAggregator.GetEvent<MsgEvent>().Publish("服务器忙...");
            }
        }



        //框架自带的接口实现
        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }

        #endregion


        #region 最小化与关闭

        /// <summary>
        /// 最小化
        /// </summary>

        public DelegateCommand BtnMinCmd { get; set; }
        public DelegateCommand BtnCloseCmd { get; set; }


        //修改窗体状态的属性
        private WindowState myWindowState;

        public WindowState MyWindowState
        {
            get { return myWindowState; }
            set
            {
                myWindowState = value;
                RaisePropertyChanged();
            }
        }


        private void BtnMinFunc()
        {
            if (MyWindowState != null)
                MyWindowState = WindowState.Minimized;
        }

        /// <summary>
        /// 关闭
        /// </summary>
        private void BtnCloseFunc()
        {
            Environment.Exit(0);
        }
        #endregion


        #region 按下enter自动登录

        public DelegateCommand KeyDownLoginCmd { get; set; }

        public void KeyDownLoginFunc()
        {
            LoginSystemFunc();
        }
        #endregion
    }
}
